package com.example.demo.controller;

import com.example.demo.model.Teacher;
import com.example.demo.service.TeacherService;
import com.example.demo.service.UserService;
import com.example.demo.service.ImportService;
import com.example.demo.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/teachers")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ImportService importService;

    // 获取所有教师（支持分页和搜索）
    @GetMapping
    public Page<Teacher> getAllTeachers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false, defaultValue = "") String teacherNo,
            @RequestParam(required = false, defaultValue = "") String name) {
        
        // 如果有搜索条件，则执行搜索，否则获取所有教师
        if (!teacherNo.isEmpty() || !name.isEmpty()) {
            return teacherService.searchTeachers(teacherNo, name, page, size);
        } else {
            return teacherService.getAllTeachers(page, size);
        }
    }

    // 根据ID获取教师
    @GetMapping("/{id}")
    public ResponseEntity<Teacher> getTeacherById(@PathVariable Long id) {
        Optional<Teacher> teacher = teacherService.getTeacherById(id);
        if (teacher.isPresent()) {
            return ResponseEntity.ok(teacher.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建教师
    @PostMapping
    public Teacher createTeacher(@RequestBody Teacher teacher) {
        return teacherService.saveTeacher(teacher);
    }

    // 更新教师
    @PutMapping("/{id}")
    public ResponseEntity<Teacher> updateTeacher(@PathVariable Long id, @RequestBody Teacher teacherDetails) {
        Optional<Teacher> teacher = teacherService.getTeacherById(id);
        if (teacher.isPresent()) {
            Teacher updatedTeacher = teacher.get();
            updatedTeacher.setUserId(teacherDetails.getUserId());
            updatedTeacher.setTeacherNo(teacherDetails.getTeacherNo());
            updatedTeacher.setCollegeId(teacherDetails.getCollegeId());
            updatedTeacher.setTitle(teacherDetails.getTitle());
            updatedTeacher.setEmploymentDate(teacherDetails.getEmploymentDate());
            teacherService.saveTeacher(updatedTeacher);
            return ResponseEntity.ok(updatedTeacher);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除教师
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTeacher(@PathVariable Long id) {
        Optional<Teacher> teacher = teacherService.getTeacherById(id);
        if (teacher.isPresent()) {
            // 先删除教师记录
            teacherService.deleteTeacher(id);
            // 再删除对应的用户记录
            userService.deleteUser(teacher.get().getUserId());
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据工号获取教师
    @GetMapping("/teacherNo/{teacherNo}")
    public ResponseEntity<Teacher> getTeacherByTeacherNo(@PathVariable String teacherNo) {
        Optional<Teacher> teacher = teacherService.getTeacherByTeacherNo(teacherNo);
        if (teacher.isPresent()) {
            return ResponseEntity.ok(teacher.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据用户ID获取教师
    @GetMapping("/user/{userId}")
    public ResponseEntity<Teacher> getTeacherByUserId(@PathVariable Long userId) {
        Optional<Teacher> teacher = teacherService.getTeacherByUserId(userId);
        if (teacher.isPresent()) {
            return ResponseEntity.ok(teacher.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    // 下载教师导入模板
    @GetMapping("/template")
    public ResponseEntity<byte[]> downloadTeacherTemplate() {
        try {
            byte[] template = ExcelUtils.createTeacherTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "教师导入模板.xlsx");
            return new ResponseEntity<>(template, headers, HttpStatus.OK);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    // 导入教师数据
    @PostMapping("/import")
    public ResponseEntity<String> importTeachers(@RequestParam("file") MultipartFile file) {
        try {
            String result = importService.importTeachers(file);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("导入失败: " + e.getMessage());
        }
    }
    
    // 导出所有教师列表
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportAllTeachers() {
        try {
            // 获取所有教师
            List<Teacher> teachers = teacherService.getAllTeachersForExport();
            
            // 导出为Excel
            byte[] excelData = ExcelUtils.exportTeachersToExcel(teachers);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "教师列表.xlsx");
            
            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}